今天想要分享另一個我在 Youtube 上面看到的教學,
是個眼球會隨著你的滑鼠移動的小練習,
影片連結在此。
覺得 JS 有好多種 X、Y,
常常記不起來各是指什麼樣的距離,
之後有機會再來好好整理一番,
以下一樣分享我寫的程式碼。
效果
HTML
<div class="face">
<div class="eyes">
<div class="eye"></div>
<div class="eye"></div>
</div>
</div>
CSS
* {
padding: 0;
margin: 0;
list-style: none;
}
body {
height: 100vh;
display: flex;
align-items: center;
background-color: #95a5a6;
}
.face {
width: 400px;
height: 400px;
margin: auto;
background-color: #f1c40f;
border-radius: 50%;
position: relative;
display: flex;
justify-content: center;
align-items: center;
box-shadow: 0 0 20px 10px rgba(0, 0, 0, .2);
}
.face::after {
content: '';
position: absolute;
width: 210px;
height: 100px;
background-color: #c0392b;
left: 0;
right: 0;
margin: auto;
bottom: 50px;
border-radius: 0 0 100px 100px;
transition: .5s;
}
.face:hover::after {
bottom: 80px;
height: 40px;
border-radius: 0;
}
.eyes {
display: flex;
position: relative;
top: -60px;
}
.eye {
width: 120px;
height: 120px;
margin: 15px;
background-color: #fff;
border-radius: 50%;
position: relative;
}
.eye::before {
content: '';
position: absolute;
width: 60px;
height: 60px;
background-color: #222;
border-radius: 50%;
top: 50%;
left: 25%;
transform: translate(-50%, -50%);
}
JS
document.querySelector('body').addEventListener('mousemove', eyeballMove);
function eyeballMove() {
const eye = document.querySelectorAll('.eye');
eye.forEach(eye => {
let x = eye.getBoundingClientRect().left + eye.clientWidth / 2;
let y = eye.getBoundingClientRect().top + eye.clientHeight / 2;
let rad = Math.atan2(event.pageX - x, event.pageY - y);
let rot = -rad * 180 / Math.PI + 270;
eye.style.transform = `rotate(${rot}deg)`;
})
}
今天就先到這裡啦~
我們明天見。